<template>
  <div>
    <el-divider />
    <el-row>
      <el-col :span="12">
        <el-form-item label="任务名称" prop="taskName">
          <el-input
            v-model="form.taskName"
            :disabled="form.isHiddenValu"
            placeholder="请输入任务名称"
            style="width: 204px"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="迁移类型" prop="convertType">
          <el-select v-model="form.convertType" :disabled="form.isHiddenValu" placeholder="请选择迁移类型" clearable filterable @change="convertTypeChange">
            <el-option
              v-for="item in convertTypeList"
              :key="item.name"
              :label="item.name"
              :value="item.name"
              :disabled="!item.enabled"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <!-- <el-form-item label="导入方式" prop="scriptImportType">
        <el-radio-group v-model="form.scriptImportType" @change="initDbList">
          <el-radio-button :disabled="form.isHiddenValu || form.isHiddenImportType" label="FILE">文件导入</el-radio-button>
          <el-radio-button disabled label="DATABASE">数据库直连</el-radio-button>
        </el-radio-group>
      </el-form-item> -->
    </el-row>
    <el-row>
      <el-col :span="12">
        <el-form-item label="源服务器" prop="sourceConnCode">
          <el-select v-model="form.sourceConnCode" clearable filterable :disabled="form.isHiddenValu" placeholder="请选择源服务器" @change="initDbList">
            <el-option
              v-for="item in sourceConnList"
              :key="item.sourceCode"
              :label="item.sourceName"
              :value="item.sourceCode"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="目标服务器" prop="targetConnCode">
          <el-select v-model="form.targetConnCode" clearable filterable :disabled="form.isHiddenValu" placeholder="请选择目标服务器">
            <el-option
              v-for="item in targetConnList"
              :key="item.sourceCode"
              :label="item.sourceName"
              :value="item.sourceCode"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-form-item v-if="form.scriptImportType === 'DATABASE'" label="数据库名" prop="dbName">
        <el-select
          v-model="form.dbName"
          filterable
          :disabled="form.isHiddenValu"
          placeholder="请选择数据库名"
          @change="showProceduresList"
        >
          <el-option v-for="dbName in dbList" :key="dbName" :label="dbName" :value="dbName" />
        </el-select>
      </el-form-item>
    </el-row>
    <div v-if="form.scriptImportType === 'FILE'">
      <el-input
        v-model="queryFileName"
        clearable
        size="small"
        placeholder="请输入脚本文件名称搜索"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="toQuery"
      />
      <span style="margin-left: 10px">
        <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
        <el-button class="filter-item" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery">重置</el-button>
        <el-upload
          v-if="form.scriptImportType === 'FILE'"
          ref="upload"
          class="upload-demo"
          action=""
          multiple
          :auto-upload="true"
          :disabled="form.isHiddenUploadFile"
          :before-upload="handleBeforeUpload"
          :on-change="handleChange"
          :http-request="uploadRequest"
          :on-success="handleSuccess"
          :on-error="handleError"
          :file-list="fileList"
          :show-file-list="false"
        >
          <div>
            <el-button size="small" :disabled="form.isHiddenUploadFile" type="primary">点击上传</el-button>
          </div>
        </el-upload>
      </span>
      <el-table
        ref="table"
        style="margin-top: 10px"
        border
        :data="form.fileList"
        row-key="id"
        max-height="235"
      >
        <el-table-column prop="fileName" label="脚本文件名称" />
        <el-table-column prop="option" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" :disabled="form.isHiddenValu" @click="bitchTableDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="form.scriptImportType === 'DATABASE'" style="margin-left: 50px">
      <el-transfer
        v-model="form.proceduresList"
        filterable
        :titles="['源存储过程列表', '待转换存储过程列表']"
        :format="{ noChecked: '${total}', hasChecked: '${checked}/${total}'}"
        :data="proceduresList"
      />
    </div>
  </div>
</template>
<script>
import scriptConvertTaskApi from '@/api/script/transfer/script-convert-task'
import scriptConvertListApi from '@/api/script/transfer/script-convert-list'
import dataSourceApi from '@/api/metadata/dataSource'
import { crunDate } from '@utils/data'

export default {
  name: 'ScriptConvertList',
  model: {
    prop: 'form',
    event: 'changes'
  },
  props: {
    form: {
      required: true,
      type: Object
    },
    crud: {
      required: true,
      type: Object
    }
  },
  data() {
    return {
      queryFileName: null,
      proceduresList: [],
      convertTypeList: [],
      sourceConnList: [],
      targetConnList: [],
      dbList: [],
      fileList: []
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      if (this.form.convertType !== undefined && this.form.convertType !== null && this.form.convertType !== '') {
        this.convertTypeChange(this.form.convertType)
      }
      if (this.form.pkId) {
        const params = {
          convertTaskPkId: this.form.pkId
        }
        scriptConvertListApi.findListByPage(params).then(res => {
          this.form.fileList = res.content.map(fileInfo => {
            const file = {}
            file.fileName = fileInfo.sourceFileName
            file.filePath = fileInfo.sourceFileAbsolutePath
            return file
          })
        }).catch(err => {
          console.log(err)
        })
      }
      this.initConvertTypeList()
      if (this.crud.status.add) {
        this.form.taskName = `脚本迁移-${crunDate()}`
        dataSourceApi.findDefaultSource().then(data => {
          const sourceDefault = data.find(item => item.isDefault === 'ENABLE' && item.sourceAttribute === 'source')
          const targetDefault = data.find(item => item.isDefault === 'ENABLE' && item.sourceAttribute === 'target')
          const convertType = (sourceDefault === undefined ? '' : sourceDefault.sourceType) + '-' + (targetDefault === undefined ? '' : targetDefault.sourceType)
          if (this.convertTypeList.some(item => item.name === convertType && item.enabled === true)) {
            this.form.convertType = convertType
            this.convertTypeChange(this.form.convertType)
            this.form.sourceConnCode = sourceDefault === undefined ? '' : sourceDefault.sourceCode
            this.form.targetConnCode = targetDefault === undefined ? '' : targetDefault.sourceCode
          }
        })
      }
    },
    initConvertTypeList() {
      scriptConvertTaskApi.getMigrationTypeInfos().then(res => {
        this.convertTypeList = res
      })
    },
    convertTypeChange(convertType) {
      const sourceTypes = convertType.split('-')
      this.initSourceConnList(sourceTypes[0])
      this.initTargetConnList(sourceTypes[1])
    },
    initSourceConnList(sourceType) {
      const params = { serverType: 'SOURCE', sourceType: sourceType, size: 10000 }
      dataSourceApi.findListByPage(params).then(res => {
        if (res.total > 0) {
          this.sourceConnList = res.content
        }
      })
    },
    initTargetConnList(targetType) {
      const params = { serverType: 'TARGET', sourceType: targetType, size: 10000 }
      dataSourceApi.findListByPage(params).then(res => {
        if (res.total > 0) {
          this.targetConnList = res.content
        }
      })
    },
    handleBeforeUpload(file) {
      // 判断文件是否重复上传
      if (this.form.fileList.map(item => item.fileName).includes(file.name)) {
        setTimeout(() => {
          this.$message.warning(`${file.name} 已在列表中,请勿重复上传!`)
        }, 10)
        return false
      }
      return true
    },
    uploadRequest(options) {
      const { file, onSuccess, onError } = options
      // 创建一个 FormData 对象
      const formData = new FormData()
      formData.append('file', file)
      scriptConvertTaskApi.upload(formData).then(res => {
        onSuccess(res)
      }).catch(error => {
        onError(error)
      })
    },
    handleSuccess(response, file, fileList) {
      response.forEach(filePath => {
        let fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
        if (filePath.includes('\\')) {
          fileName = filePath.substring(filePath.lastIndexOf('\\') + 1)
        }
        const dataForm = { filePath: filePath, fileName: fileName }
        this.form.fileList.push(dataForm)
      })
    },
    handleError(error, file) {
      this.$message.error(`${file.name} 上传失败！`)
      console.error('文件上传失败', error)
    },
    handleChange(file, fileList) {
      // this.fileList = fileList
    },
    initDbList() {
      if (this.form.scriptImportType === 'DATABASE' && this.form.sourceConnPkId !== undefined &&
        this.form.sourceConnPkId !== null && this.form.sourceConnPkId !== '') {
        dataSourceApi.schemas(this.form.sourceConnPkId).then(data => {
          this.dbList = data
        })
      }
    },
    showProceduresList() {
      const params = { pkId: this.form.sourceConnPkId, schema: this.form.dbName }
      this.proceduresList = []
      dataSourceApi.procedures(params).then(data => {
        if (data instanceof Array && data.length > 0) {
          data.forEach(proceduresName => {
            this.proceduresList.push({
              key: proceduresName,
              label: proceduresName
            })
          })
        }
      })
    },
    bitchTableDelete(row) {
      this.$confirm(`确认删除待转换脚本【` + row.fileName + `】?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const newArr = this.form.fileList.filter(item => item.filePath !== row.filePath)
        this.form.fileList = newArr
      }).catch(() => {
      })
    },
    toQuery() {
      // 搜索框有内容时搜索
      if (this.queryFileName) {
        this.form.tmpFileList = JSON.parse(JSON.stringify(this.form.fileList))
        const newArr = this.form.fileList.filter(item => item.fileName && item.fileName.toUpperCase().includes(this.queryFileName.toUpperCase()))
        this.form.fileList = newArr
        this.$forceUpdate()
      }
    },
    resetQuery() {
      this.queryFileName = null
      this.form.fileList = JSON.parse(JSON.stringify(this.form.tmpFileList))
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.upload-demo {
  display: inline-block;
  margin-left: 10px;
}
::v-deep .el-transfer-panel {
  width: 450px !important;
}

::v-deep .bordered-button {
  border: #92dab3 2px;
}

::v-deep .el-transfer__buttons button {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

::v-deep .el-transfer__buttons button:last-child {
  margin-left: 0px;
}
</style>
